package day9;

class Bus extends Thread {

    // 票数
    static int tickets = 80;

    public Bus (String name) {
        super(name);
    }

    @Override
    public void run() {
        while (true) {

            synchronized (Bus.class) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(this.getName() + "车上剩余位置:" + (tickets--) + "个");
                } else {
                    break;
                }
            }
        }
    }
}

class Bus2 {
    static int tickets = 80;

    public void shangche() {
        while (true) {

            synchronized (Bus.class) {
                if (tickets > 0) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "车上剩余位置:" + (tickets--) + "个");
                } else {
                    break;
                }
            }
        }
    }
}

public class Demo7 {

    public static void main(String[] args) {
        Bus s1 = new Bus("前门");
        Bus s2 = new Bus("中门");
        Bus s3 = new Bus("后门");

        s1.start();
        s2.start();
        s3.start();

//        final Bus2 b = new Bus2();
//        new Thread("前门"){
//            @Override
//            public void run() {
//                b.shangche();
//            }
//        }.start();
//        new Thread("中门"){
//            @Override
//            public void run() {
//                b.shangche();
//            }
//        }.start();
//        new Thread("后门"){
//            @Override
//            public void run() {
//                b.shangche();
//            }
//        }.start();
    }
}
